import { NextRequest, NextResponse } from 'next/server';
import { getToken } from 'next-auth/jwt';

/**
 * @author        lx <1154354121@qq.com>
 * @date          2025-04-14 11:31:53
 * Copyright © YourCompanyName All rights reserved
 */
const needLoginFullPaths = ['/']; // 需要登录的全匹配路径
const needLoginStartPaths = ['/user']; // 需要登录的前缀匹配路径
const needLoginRegPaths = [/order\/.+/]; // 需要登录的正则匹配路径
const ignorePaths = ['/login', '/register']; // 不需要登录的路径
export const authMiddleware = async (request: NextRequest) => {
  try {
    const token = await getToken({
      req: request,
      secret: process.env.NEXTAUTH_SECRET,
    });
    console.log(
      'xxxxxxxxxxxauthMiddlewarexxxxxxxxxxx',
      request.nextUrl.pathname,
      token + ' ads'
    );
    // const session = await getServerSession(authOptions); // 从服务器获取会话信息
    // console.log('--------------------', request.nextUrl.pathname, session);
    if (
      !ignorePaths.includes(request.nextUrl.pathname) &&
      (needLoginFullPaths.includes(request.nextUrl.pathname) ||
        needLoginStartPaths.some((path) =>
          request.nextUrl.pathname.startsWith(path)
        ) ||
        needLoginRegPaths.some((path) =>
          path.test(request.nextUrl.pathname)
        )) &&
      !token
    ) {
      // 未登录，重定向到登录页面
      return NextResponse.redirect(new URL('/login', request.url));
    }
    return NextResponse.next();
  } catch (error) {
    console.log(error);
    return NextResponse.next();
  }
};

export const authConfig = {
  matcher: [
    '/((?!api).*)', // 只匹配页面
  ],
};
